package it.rockliveitalia;

import it.rockliveitalia.database.EventDbHelper;
import it.rockliveitalia.entity.Event;
import it.rockliveitalia.tool.Parser;
import it.rockliveitalia.tool.Sender;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.xml.sax.SAXException;

import com.google.analytics.tracking.android.EasyTracker;

import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;

public class SetupMapActivity extends Activity {

	private Context context;
	private List<File> fileList;
	private Date date;
	private SharedPreferences prefs;
	private AsyncTask<Void, Void, String> as;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_setup_map);
		context = getApplicationContext();
		prefs = PreferenceManager.getDefaultSharedPreferences(context);
		String dateString = prefs.getString("lastDownload",
				getString(R.string.initial_date));
		boolean firstTime = prefs.getBoolean("firstTime", true);
		Event e = new Event();
		e.setDate(dateString);
		final Sender s = new Sender();
		date = e.getDate();
		fileList = s.createFile(this, date, firstTime);
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.MINUTE, 1);
		EventDbHelper helper = new EventDbHelper(context);
		helper.deleteOldEvents(cal.getTimeInMillis());
		if (firstTime) {
			try {

				as = new AsyncTask<Void, Void, String>() {
					@Override
					public String doInBackground(Void... arg) {
						String lastDownload = null;

						try {
							lastDownload = s.download(fileList, date);
						} catch (Exception e) {
							e.printStackTrace();
						}
						return lastDownload;
					}

					@Override
					protected void onPostExecute(String result) {
						launchActivity(fileList, result);
					}

					private void launchActivity(List<File> list, String result) {

						Parser p = new Parser();
						EventDbHelper helper = new EventDbHelper(context);
						List<Event> eventList = new ArrayList<Event>();

						boolean flag = false;
						for (File file : list) {
							try {
								eventList.addAll(p.parseXml(file));
							} catch (SAXException e) {
								e.printStackTrace();
								flag = true;
							}
						}
						for (Event e : eventList) {
							helper.insertEvent(e);
						}
						SharedPreferences.Editor editor = prefs.edit();
						Intent intent = new Intent(context, MapActivity.class);
						intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						if (result != null) {
							if (!result.equals("NoConnection") && !flag) {
								editor.putBoolean("firstTime", false);
								editor.putString("lastDownload", result);
								editor.commit();
								intent.putExtra("fileLoaded", true);
							} else {
								intent.putExtra("fileLoaded", false);
							}
						} else {
							intent.putExtra("fileLoaded", false);
						}
						startActivity(intent);
						finish();
					}
				}.execute();

			} catch (Exception exception) {
				exception.printStackTrace();
			}
		} else {
			Intent intent = new Intent(context, MapActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			intent.putExtra("fileLoaded", true);
			intent.putExtra("setup", true);

			startActivity(intent);
			finish();
		}

	}

	@Override
	public void onStart() {
		super.onStart();
		EasyTracker.getInstance(this).activityStart(this);
	}

	@Override
	protected void onStop() {
		super.onStop();
		EasyTracker.getInstance(this).activityStop(this);
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		as.cancel(false);
		finish();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		for (File file : fileList) {
			file.delete();
		}
	}

}
